package com.north.light.libnorthlightbullet.task;

import com.north.light.libnorthlightbullet.BulletApi;
import com.north.light.libnorthlightbullet.constant.DrawConstant;

import java.io.Serializable;
import java.util.Timer;
import java.util.TimerTask;

/**
 * FileName: DrawTask
 * Author: lzt
 * Date: 2023/1/13 20:15
 * 绘制任务队列
 */
public class DrawTask implements Serializable {
    //定时任务
    private Timer mTimer;
    private TimerTask mCheckTask;
    private long TASK_CHECK_INTERVAL = DrawConstant.CON_TASK_INTERVAL;
    private BulletApi mBulletViewApi;

    private final Object SYN = new Object();

    public DrawTask(BulletApi bulletApi) {
        this.mBulletViewApi = bulletApi;
    }

    private void startTask() {
        removeTask();
        mCheckTask = new TimerTask() {
            @Override
            public void run() {
                if (mBulletViewApi != null) {
                    mBulletViewApi.timer(TASK_CHECK_INTERVAL);
                }
            }
        };
        mTimer = new Timer();
        mTimer.schedule(mCheckTask, 0, TASK_CHECK_INTERVAL);
    }


    private void removeTask() {
        if (mCheckTask != null) {
            mCheckTask.cancel();
        }
        if (mTimer != null) {
            mTimer.cancel();
        }
    }

    //外部调用--------------------------------------------------

    public void release() {
        synchronized (SYN) {
            removeTask();
        }
    }

    public void start() {
        synchronized (SYN) {
            removeTask();
            startTask();
        }
    }

}
